<template>
  <div>
    <h1>{{ id ? '编辑' : '新建' }}文章</h1>
    <el-form label-width="100px">
      <el-form-item label="所属分类">
        <el-select v-model="model.categories" multiple>
          <el-option v-for="item in categories" :key="item._id" :label="item.name" :value="item._id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="文章标题">
        <el-input v-model="model.title"></el-input>
      </el-form-item>
      <el-form-item label="文章内容">
        <vue-editor v-model="model.body" useCustomImageHandler @image-added="handleImageAdded"></vue-editor>
        <!-- <vue2-editor v-model="model.body" :editorToolbar="customToolbar"></vue2-editor> -->
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit" @click="save">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { VueEditor } from 'vue2-editor';
export default {
  components: {
    VueEditor,
  },
  props: {
    id: {},
  },
  data() {
    return {
      model: {},
      categories: [], // 分类名称
    };
  },

  created() {
    this.id && this.fetch();
    this.fetchCategories();
  },

  methods: {
    async save() {
      if (!this.model.title) {
        this.$message({
          showClose: true,
          message: '请填写分类',
        });
        return;
      }
      let res;
      let message = '';
      // 根据id的有无 判断是新增还是修改
      if (this.id) {
        res = await this.axios.put(`rest/articles/${this.id}`, this.model);
        message = '修改成功';
      } else {
        res = await this.axios.post('rest/articles', this.model);
        message = '添加成功';
      }

      this.$message({
        showClose: true,
        message: message,
        type: 'success',
      });

      setTimeout(() => {
        this.$router.push('/articles/list');
      }, 500);
    },

    async fetch() {
      const res = await this.axios.get(`rest/articles/${this.id}`);
      this.model = res.data;
    },

    // 获取父级分类
    async fetchCategories() {
      const res = await this.axios.get(`rest/categories`);
      this.categories = res.data;
    },

    // 图片上传
    async handleImageAdded(file, Editor, cursorLocation, resetUploader) {
      const formData = new FormData();
      formData.append('file', file);

      let res = await this.axios.post('upload', formData);
      Editor.insertEmbed(cursorLocation, 'image', res.data.url);
      resetUploader();
    },
  },
};
</script>
<style scoped></style>;
